package com.yangye.pidoublename.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yangye.pidoublename.service.DoubleNameService;
import com.yangye.pidoublename.service.ProvinceEnum;
import com.yangye.pidoublename.vo.DoubleNameVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @author yangye
 * @date 2019/9/19
 */
@Service
public class JiLinServiceImpl implements DoubleNameService {

	@Autowired
	private RestTemplate restTemplate;

	private final String QUERY_URL = "http://gafw.jl.gov.cn/MainPages/ChaXunZhongXin/CommInsertData";

	@Override
	public DoubleNameVo findByName(String name) {
		MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
		params.add("ActionName", "010106");
		JSONObject param = new JSONObject();
		param.put("xm", name);
		params.add("CommndName", param.toJSONString());
		HttpHeaders httpHeaders = new HttpHeaders();
		httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
		HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(params, httpHeaders);
		JSONObject resutlJson = restTemplate.postForObject(QUERY_URL, request, JSONObject.class);
		String result = resutlJson.getString("Result");
		JSONObject data = JSON.parseObject(result);
		Integer total = 0;
		if (data != null) {
			total = data.getInteger("count");
		}
		DoubleNameVo doubleNameVo = new DoubleNameVo();
		doubleNameVo.setProvince(ProvinceEnum.JILIN.getName());
		doubleNameVo.setName(name);
		doubleNameVo.setTotal(total);
		return doubleNameVo;
	}
}
